package assdraw2.intermediate.control;

import assdraw2.canvas.CanvasControl;
import assdraw2.coloragent.ColorControl;
import assdraw2.common.MessageType;
import assdraw2.common.PACAgent;
import assdraw2.common.PACMessage;
import assdraw2.toolbaragent.ToolbarControl;

public class DrawingIntermediateAgent implements PACAgent{

	private CanvasControl canvas;
	private ColorControl colorAgent;
	private ToolbarControl toolbarAgent; 
	
	private PACAgent parent;
	
	public DrawingIntermediateAgent(PACAgent parent){
		super();
		this.parent = parent;
	}
	
	
	@Override
	public void receiveMessage(PACMessage m) {
		if(m.getType() == MessageType.OPEN){
			getAgentFromId(m.getId()).receiveMessage(m);
			
		}else if(m.getType() == MessageType.CLOSE){
			if(m.getSource() == null){
				getAgentFromId(m.getId()).receiveMessage(m);
			}else{
				parent.receiveMessage(m);
			}

		}else if(m.getType() == MessageType.TOOL || m.getType() == MessageType.COLOR ||
				m.getType() == MessageType.ZOOM_IN ||
				m.getType() == MessageType.ZOOM_OUT) {
			if(canvas != null){
				canvas.receiveMessage(m);
			}
		}else if(m.getType() == MessageType.SHAPE_GROUP ||
		m.getType() == MessageType.SHAPE_UNGROUP || m.getType() == MessageType.SIZE_DOWN||
		m.getType() == MessageType.SIZE_UP){
			if(canvas != null){
				canvas.receiveMessage(m);
			}
			parent.receiveMessage(m);
		}
		else{
			parent.receiveMessage(m);
		}
		
	}

	private PACAgent getAgentFromId(int id){
		switch(id){
		case 0:
			if(canvas == null){
				canvas = new CanvasControl(this);
				return canvas;
			}else{
				return canvas;
			}
		case 1:
			if(canvas == null){
				canvas = new CanvasControl(this);
			}
			if(toolbarAgent == null){
				toolbarAgent = new ToolbarControl(this);
				return toolbarAgent;
			}else{
				return toolbarAgent;
			}		
		case 2:
			if(canvas == null){
				canvas = new CanvasControl(this);
			}
			if(colorAgent == null){
				colorAgent = new ColorControl(this);
				return colorAgent;
			}else{
				return colorAgent;
			}
		
		}	
		return null;
	}
	
	@Override
	public void sendMessage(PACMessage m) {
		// TODO Auto-generated method stub
		
	}
	

	public PACAgent getParentAgent() {
		return parent;
	}

}
